package cn.sinata.wanglin.neighbor.fragment;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.fragment.BaseLazyFragment;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;
import com.xilada.xldutils.view.SwipeRefreshRecyclerLayout;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import cn.sinata.wanglin.MyApplication;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.adapter.CircleAdapter;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.db.dao.PushDao;
import cn.sinata.wanglin.model.Circle;
import cn.sinata.wanglin.model.Comment;
import cn.sinata.wanglin.neighbor.activity.CircleDetailActivity;
import cn.sinata.wanglin.neighbor.activity.EditCommentActivity;
import cn.sinata.wanglin.neighbor.activity.MineCircleActivity;
import cn.sinata.wanglin.neighbor.activity.NewCircleMessageActivity;
import cn.sinata.wanglin.neighbor.controller.FriendCircleListener;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.PushData;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import cn.sinata.wanglin.utils.ImageUtil;
import cn.sinata.wanglin.utils.RxBus;
import rx.Observable;
import rx.functions.Action1;

/**
 *
 * Created by liaoxiang on 16/12/13.
 */

public class CircleFragment extends BaseLazyFragment implements SwipeRefreshRecyclerLayout.OnRefreshListener{

    @BindView(R.id.mSwipeRefreshLayout)
    SwipeRefreshRecyclerLayout mSwipeRefreshLayout;
    private ArrayList<Circle> mCircles = new ArrayList<>();
    private CircleAdapter circleAdapter;
    private View ll_message;
    private SimpleDraweeView headImageView;
    private TextView tv_message;
    private int pageNo = 0;
    private String userId;
    private Observable<String> publishOb;


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_circle_layout;
    }

    @Override
    protected void onFirstVisibleToUser() {

        publishOb = RxBus.get().register(Constant.PUBLISH_CIRCLE_ACTION,String.class);

        publishOb.subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                onRefresh();
            }
        });

        userId = SharedPreferencesUtils.getString(Constant.SP_USERID);
        mSwipeRefreshLayout.setLayoutManager(new LinearLayoutManager(context));
        circleAdapter = new CircleAdapter(mCircles);
        final View headerView = View.inflate(context,R.layout.header_circle_message_layout,null);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        headerView.setLayoutParams(params);
        headerView.requestLayout();
        ll_message = headerView.findViewById(R.id.ll_message);
        headImageView = (SimpleDraweeView) headerView.findViewById(R.id.headView);
        tv_message = (TextView) headerView.findViewById(R.id.tv_message);
        ll_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ll_message.setVisibility(View.GONE);
                ActivityUtil.create(CircleFragment.this)
                        .go(NewCircleMessageActivity.class)
                        .start();
            }
        });
        circleAdapter.setHeaderView(headerView);
        mSwipeRefreshLayout.setAdapter(circleAdapter);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.addItemDecoration(new HorizontalDividerItemDecoration.Builder(context)
                .drawable(R.drawable.circle_divider_line)
                .size(2)
                .build());
        circleAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ActivityUtil.create(context)
                        .go(CircleDetailActivity.class)
                        .put("id",mCircles.get(position).getId())
                        .put("toUser",mCircles.get(position).getAuthorId())
                        .startForResult(0);
            }
        });

        circleAdapter.setListener(new FriendCircleListener() {
            @Override
            public void showAllToggle() {

            }

            @Override
            public void onAvatarClick(int position, String id) {
                ActivityUtil.create(context)
                        .go(MineCircleActivity.class)
                        .put("id",id)
                        .start();
            }

            @Override
            public void onCommentButtonClick(int position, Comment comment) {
                Circle circle = mCircles.get(position);
                ActivityUtil.create(CircleFragment.this)
                        .go(EditCommentActivity.class)
                        .put("id",circle.getId())
                        .put("position",position)
                        .put("toUser",comment.getId())
                        .put("name",comment.getFromNick())
                        .put("commentId",comment.getCommentId())
                        .startForResult(12);
            }

            @Override
            public void onPraiseButtonClick(int position, String id) {

            }

            @Override
            public void onCommentItemClick(int position, Comment comment) {
                Circle circle = mCircles.get(position);
                ActivityUtil.create(CircleFragment.this)
                        .go(EditCommentActivity.class)
                        .put("id",circle.getId())
                        .put("toUser",comment.getId())
                        .put("position",position)
                        .put("name",comment.getFromNick())
                        .put("type",1)
                        .put("commentId",comment.getCommentId())
                        .startForResult(12);
            }

            @Override
            public void onLinkNameClick(String id) {

            }

            @Override
            public void onDelete(int position, String id) {

            }
        });

        unReadSet();

        showDialog();
        getData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Utils.systemErr("----onActivityResult----");
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 12) {
                if (data != null) {
                    int position = data.getIntExtra("position",0);
                    Comment comment = (Comment) data.getSerializableExtra("data");
                    if (position >= 0 && position < mCircles.size()) {
                        if (mCircles.get(position).getCommentList() == null) {
                            return;
                        }
                        mCircles.get(position).getCommentList().add(comment);
                        int commentNum = mCircles.get(position).getCommentNum();
                        mCircles.get(position).setCommentNum(commentNum+1);
                        circleAdapter.notifyDataSetChanged();
                    }
                }
            }
        }
    }

    void unReadSet(){
        if (MyApplication.circleUnRead > 0) {
            String account = SharedPreferencesUtils.getString(Constant.SP_IM_ACCOUNT);
            PushData data = PushDao.getInstance(context).getLastUnReadCircleNewMessage(account);
            String ext = data.getExt();
            try {
                JSONObject jsonObject = new JSONObject(ext);
                headImageView.setImageURI(ImageUtil.parseImageUri(jsonObject.optString("headUrl")));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            tv_message.setText(MyApplication.circleUnRead+"条新消息");
            ll_message.setVisibility(View.VISIBLE);
        } else {
            ll_message.setVisibility(View.GONE);
        }
    }


    @Override
    protected void onVisibleToUser() {
        unReadSet();
    }

    @Override
    protected void onInvisibleToUser() {

    }

    void getData(){
        HttpManager.getFriendCircleList(userId,pageNo)
                .subscribe(new ResultDataSubscriber<ArrayList<Circle>>(this) {
                    @Override
                    public void onSuccess(String msg, ArrayList<Circle> circles) {
                        mSwipeRefreshLayout.setRefreshing(false);
                        if (pageNo == 0) {
                            mCircles.clear();
                        }
                        if (circles.size() == 0) {
                            if (pageNo == 0) {
                                mSwipeRefreshLayout.setLoadMoreText("暂无数据");
                            } else {
                                pageNo --;
                                mSwipeRefreshLayout.setLoadMoreText("没有更多了");
                            }
                        }
                        mCircles.addAll(circles);
                        circleAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    @Override
    public void onRefresh() {
        pageNo = 0;
        getData();
    }

    @Override
    public void onLoadMore() {
        pageNo++;
        getData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            if (publishOb != null) {
                RxBus.get().unregister(Constant.PUBLISH_CIRCLE_ACTION,publishOb);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
